package top.yzlin.jqueryjx3strategystation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.yzlin.jqueryjx3strategystation.dao.UserDAO;
import top.yzlin.jqueryjx3strategystation.entity.user.BaseUser;
import top.yzlin.jqueryjx3strategystation.entity.user.User;
import top.yzlin.jqueryjx3strategystation.entity.vo.ResponseVO;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.regex.Pattern;

@RestController
public class UserController {
    private UserDAO userDAO;
    private static final Pattern PASSWORD_PATTERN=Pattern.compile("^\\w{4,10}$");

    @Autowired
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @PostMapping("/user/register")
    public ResponseVO register(@Valid User user){
        if (userDAO.isExistUserByUserName(user.getUserName())) {
            return ResponseVO.createInstance(403, "用户名已被注册");
        }
        user.setPermissions(User.ORDINARY);
        user.setPortrait("/img/test/testHead.jpg");
        userDAO.save(user);
        return ResponseVO.SUCCESS;
    }

    @PostMapping("/user/login")
    public ResponseVO login(@Valid BaseUser baseUser, HttpSession session){
        User user=userDAO.findUserByUserNameAndPassword(baseUser.getUserName(),baseUser.getPassword());
        if (user!=null) {
            session.setAttribute("user",user);
            return ResponseVO.SUCCESS;
        }else{
            return ResponseVO.createInstance(403,"登录失败，账号密码错误",null);
        }
    }

    @GetMapping("/user/logout")
    public ResponseVO logout(HttpSession session){
        session.setAttribute("user",null);
        return ResponseVO.SUCCESS;
    }

    @GetMapping("/user/info")
    public ResponseVO userInfo(@SessionAttribute(value = "user", required = false) User user) {
        return user == null ? ResponseVO.createInstance(403, "unLogin") : ResponseVO.createSuccessInstance(user);
    }

    @PostMapping("/user/update/password")
    public ResponseVO updatePasswordAction(@RequestParam("oldPassword") String oldPassword,
                                           @RequestParam("newPassword")  String newPassword,
                                           @SessionAttribute(value = "user") User user,
                                           HttpSession session){
        if (!user.getPassword().equals(oldPassword)) {
            return ResponseVO.createInstance(400,"密码错误",null);
        }
        if (!PASSWORD_PATTERN.matcher(newPassword).matches()){
            return ResponseVO.createInstance(400,"密码格式错误",null);
        }
        user.setPassword(newPassword);
        userDAO.save(user);
        session.setAttribute("user",null);
        return ResponseVO.SUCCESS;
    }
}
